<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Banner as BannerModel;
use think\Db;
use think\Log;
use think\Exception;

/**
 * APP端轮播图管理API
 */
class AppBanner extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取APP端轮播图列表
     * @ApiMethod (GET)
     * @ApiParams (name="limit", type="int", required=false, description="获取数量，默认5")
     */
    public function getBannerList()
    {
        try {
            // 获取请求参数
            $limit = $this->request->param('limit', 5, 'intval');
            
            // 获取启用状态的轮播图列表
            $banners = BannerModel::getActiveBanners($limit);
            
            // 处理图片路径
            foreach ($banners as &$banner) {
                // 处理图片路径，确保完整URL
                if (isset($banner['image']) && $banner['image']) {
                    // 检查是否为相对路径，如果是则添加域名
                    if (strpos($banner['image'], 'http') !== 0 && strpos($banner['image'], '//') !== 0) {
                        $banner['image'] = request()->domain() . $banner['image'];
                    }
                }
                
                // 格式化时间
                if (isset($banner['createtime'])) {
                    $banner['createtime'] = date('Y-m-d H:i:s', $banner['createtime']);
                }
                if (isset($banner['updatetime'])) {
                    $banner['updatetime'] = date('Y-m-d H:i:s', $banner['updatetime']);
                }
            }
            
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $banners
            ]);

        } catch (\Exception $e) {
            Log::error('获取APP轮播图列表失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }
}